import { defineStore } from 'pinia'
import { ref } from 'vue'
import { userAPI } from '@/http'

export const useUserStore = defineStore('user', () => {
  // 用户信息
  const userNickname = ref<string | null>(null)
  const token = ref<string | null>(null)
  const userImg = ref<string | null>(null)
  const isLoggedIn = ref<boolean>(false)

  // 登录信息设置
  const setLoginInfo = (nickname: string, userToken: string, userImgUrl: string) => {
    userNickname.value = nickname
    token.value = userToken
    userImg.value = userImgUrl
    isLoggedIn.value = true
    localStorage.setItem('userNickname', nickname)
    localStorage.setItem('token', userToken)
    localStorage.setItem('userImg', userImgUrl)
  }

  // 注销
  const logout = () => {
    userNickname.value = null
    token.value = null
    userImg.value = null
    isLoggedIn.value = false
    localStorage.removeItem('userNickname')
    localStorage.removeItem('token')
    localStorage.removeItem('userImg')
  }

  // 自动登录检查
  const checkAutoLogin = () => {
    const savedToken = localStorage.getItem('token')
    if (savedToken) {
      token.value = savedToken
      isLoggedIn.value = true
    }
  }

  // 注册
  const register = async (form: { username: string, email: string, phone: string, password: string }) => {
    try {
      const response = await userAPI.register(form)
      if (response.code === 200) {
        return response.data
      } else {
        throw new Error(response.message || '注册失败')
      }
    } catch (error) {
      throw new Error((error as Error).message || '网络错误')

    }
  }

  // 登录
  const login = async (form: { userTelno: string, userPwd: string }) => {
    try {
      const response = await userAPI.login(form)
      if (response.code === 200) {
        const { userNickname: nickname, token: userToken } = response.data
        setLoginInfo(nickname, userToken, '')  // 登录时没有头像信息
        return response.data
      } else {
        throw new Error(response.message || '登录失败')
      }
    } catch (error) {
      throw new Error((error as Error).message || '网络错误')

    }
  }

  // 恢复自动登录状态
  checkAutoLogin()

  return {
    userNickname,
    token,
    userImg,
    isLoggedIn,
    setLoginInfo,
    logout,
    register,
    login
  }
})